﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Web.UI.WebControls;

namespace APMAWebConsole.SettingsPart
{
    public partial class UsersList : System.Web.UI.Page
    {
        private const string TasksDataSourceKey = "TasksDataSourceKey";
        private const string UsersListKey = "UsersListKey";
        private const string ProjectsListKey = "ProjectsListKey";
        private const string UserStoriesListKey = "UserStoriesListKey";
        private const string IsEditModeKey = "IsEditModeKey";
        private const string IsUpdateKey = "IsUpdateKey";

        public DataTable UsersListData
        {
            get
            {
                return ViewState[UsersListKey] != null
                           ? (DataTable)ViewState[UsersListKey]
                           : (DataTable)(ViewState[UsersListKey] = SiteMaster.Proxy.GetUsersList());
            }

            set { ViewState[UsersListKey] = value; }
        }

        private bool IsAdmin
        {
            get
            {
                return Session[SiteMaster.IsAdminKey] != null && (bool)Session[SiteMaster.IsAdminKey];
            }
        }

        public bool IsEditMode
        {
            set { ViewState[IsEditModeKey] = value; }
            get { return ViewState[IsEditModeKey] != null && (bool) ViewState[IsEditModeKey]; }
        }

        public bool IsUpdate
        {
            set { ViewState[IsUpdateKey] = value; }
            get { return ViewState[IsUpdateKey] != null && (bool)ViewState[IsUpdateKey]; }
        }

        private int SelectedRow
        {
            get
            {
                int selectedRow;
                var isSuccessfully = int.TryParse(txtSelectedUser.Text, out selectedRow);

                if (isSuccessfully && selectedRow - 1 >= 0 && selectedRow - 1 < UsersListData.Rows.Count
                        && UsersListData.Rows[selectedRow - 1] != null)
                    return selectedRow - 1;

                return -1;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.User.Identity.IsAuthenticated)
                Response.Redirect("~/Account/Login.aspx");
        }

        private void Rebind()
        {
            if (IsEditMode)
            {
                txtUserId.Enabled = false;

                ddlUserAccessId.Items.Clear();
                ddlUserAccessId.DataValueField = "Id";
                ddlUserAccessId.DataTextField = "Name";
                ddlUserAccessId.Items.Insert(0, new ListItem(String.Empty, String.Empty));
                ddlUserAccessId.Items.Insert(1, new ListItem("Admin"));
                ddlUserAccessId.Items.Insert(2, new ListItem("User"));
                ddlUserAccessId.SelectedIndex = 0;

                if (!IsUpdate)
                {
                    txtUserId.Text = txtUserLogin.Text = txtUserPassword.Text = txtUserEmail.Text = "";
                    ddlUserAccessId.SelectedIndex = 0;
                }
                else
                {
                    var selectedRow = SelectedRow;

                    if (selectedRow == -1)
                        return;

                    txtUserId.Text = UsersListData.Rows[selectedRow]["Id"].ToString();
                    txtUserLogin.Text = UsersListData.Rows[selectedRow]["Name"].ToString();
                    txtUserPassword.Text = UsersListData.Rows[selectedRow]["Password"].ToString();
                    txtUserEmail.Text = UsersListData.Rows[selectedRow]["Email"].ToString();

                    int intParseValue;

                    var isParsed = int.TryParse(UsersListData.Rows[selectedRow]["Access_id"].ToString(), out intParseValue);
                    ddlUserAccessId.SelectedIndex = isParsed ? intParseValue : 0;
                }
            }
            else
            {
                grdUsersList.DataSource = UsersListData;
                grdUsersList.DataBind();
            }
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            divEditMode.Visible = IsEditMode && IsAdmin;
            divUsersGrid.Visible = !IsEditMode;

            btnAddUser.Visible = !IsEditMode;
            btnEditUser.Visible = btnRemoveUser.Visible = false;
            btnAddUser.Enabled = btnEditUser.Enabled = btnRemoveUser.Enabled = IsAdmin;

            grdUsersList.Columns[1].Visible = IsAdmin;
            grdUsersList.Columns[2].Visible = IsAdmin;

            btnBackToList.Visible = IsEditMode;
            btnBackToList.Enabled = IsAdmin;

            if (IsEditMode)
            {
                btnCreateUpdate.Text = IsUpdate ? "Update" : "Create";
            }

            Rebind();
        }

        protected void OnButtonCommand(object sender, CommandEventArgs e)
        {
            switch (e.CommandName)
            {
                case "Add":
                    {
                        IsEditMode = true;
                        IsUpdate = false;

                        break;
                    }
                case "Remove":
                    {
                        if (e.CommandArgument.ToString() != "")
                            txtSelectedUser.Text = e.CommandArgument.ToString();

                        RemoveUser();

                        break;
                    }
                case "Edit":
                    {
                        IsEditMode = true;
                        IsUpdate = true;

                        break;
                    }

                case "Select":
                    {
                        txtSelectedUser.Text = e.CommandArgument.ToString();
                        IsEditMode = true;
                        IsUpdate = true;

                        break;
                    }

                case "SaveUpdate":
                    {
                        if (IsEditMode)
                        {
                            if (IsUpdate)
                            {
                                UpdateUser();
                            }
                            else
                            {
                                SaveUser();
                            }
                        }

                        break;
                    }

                case "BackToList":
                    {
                        IsEditMode = false;

                        break;
                    }
            }
        }

        private Dictionary<string, object> PrepareParameters(Dictionary<string, object> parameters)
        {
            parameters.Add("Login", txtUserLogin.Text);
            parameters.Add("Password", txtUserPassword.Text);
            parameters.Add("Email", txtUserEmail.Text);
            parameters.Add("Access_id", ddlUserAccessId.SelectedIndex != 0 ? (int?)ddlUserAccessId.SelectedIndex : null);

            return parameters;
        }

        private bool ValidateFields()
        {
            Page.Validate();
            return Page.IsValid;
        }

        private void SaveUser()
        {
            if (!ValidateFields())
                return;

            var parameters = PrepareParameters(new Dictionary<string, object>());

            SiteMaster.Proxy.CreateUser(parameters, Page.User.Identity.Name);

            IsEditMode = false;
            UsersListData = null;
        }

        private void UpdateUser()
        {
            rfvUserPassword.Enabled = false;

            if (!ValidateFields())
                return;

            var parameters = new Dictionary<string, object>();

            int intParseValue;
            var isParsed = int.TryParse(txtUserId.Text, out intParseValue);

            if (!isParsed)
                return;

            parameters.Add("Id", intParseValue);

            parameters = PrepareParameters(parameters);

            if (parameters["Password"].ToString() != "")
            {
                SiteMaster.Proxy.UpdateUserWithPassword(parameters, Page.User.Identity.Name);
            }
            else {
                parameters.Remove("Password");
                SiteMaster.Proxy.UpdateUser(parameters, Page.User.Identity.Name);
            }

            IsEditMode = false;
            UsersListData = null;
        }

        private void RemoveUser()
        {
            var selectedRow = SelectedRow;

            if (selectedRow == -1)
                return;

            int intParseValue;
            var isParsed = int.TryParse(UsersListData.Rows[selectedRow]["Id"].ToString(), out intParseValue);

            if (!isParsed)
                return;

            SiteMaster.Proxy.RemoveUser(intParseValue, Page.User.Identity.Name);

            IsEditMode = false;
            UsersListData = null;
        }
    }
}